import { reqGoodsList } from '../../../api/goods'

Page({
  data: {
    goodsList: [], // 商品列表数据
    total: 0, // 数据总条数
    isFinish: false, // 判断数据是否加载完毕
    isLoading: false, // 判断数据是否加载完毕
    isEmpty: false, // 判断数据是否为空

    requestData: {
      page: 1, // 页码
      limit: 10, // 每页请求的条数
      category1Id: '', // 一级分类 id
      category2Id: '' // 二级分类 id
    }
  },

  async getGoodsList() {
    this.data.isLoading = true
    const { data } = await reqGoodsList(this.data.requestData)
    this.data.isLoading = false

    this.setData({
      goodsList: [...this.data.goodsList, ...data.records],
      total: data.total
    })
  },

  onReachBottom() {
    const { goodsList, total, requestData, isLoading } = this.data
    const { page } = requestData
    if (isLoading) return
    if (goodsList.length === total) {
      this.setData({
        isFinish: true
      })
      return
    }

    this.setData({
      requestData: { ...this.data.requestData, page: page + 1 }
    })

    this.getGoodsList()
  },

  onPullDownRefresh() {
    this.setData({
      goodsList: [],
      total: 0,
      isFinish: false,
      requestData: { ...this.data.requestData, page: 1 }
    })

    this.getGoodsList()
    wx.stopPullDownRefresh()
  },

  async onLoad(options) {
    Object.assign(this.data.requestData, options)
    await this.getGoodsList()

    this.setData({
      isEmpty: !this.data.goodsList.length
    })
  },

  gotoBack() {
    wx.navigateBack()
  },

  // 转发功能，转发给好友、群聊
  onShareAppMessage() {},

  // 能够把小程序分享到朋友圈
  onShareTimeline() {}
})
